import React, { useEffect, useRef, useState } from 'react'
import Panner from '../../../components/Panner'
import {
  Button, Table, Pagination, Modal,
  Form, Switch, Input, InputNumber, message
} from 'antd'
import { goodsAddCate, goodsCateList, goodsDelCate, goodsEditCate } from '../../../api/goods';

export default function ClassFy() {

  const [form] = Form.useForm()
  const addRef = useRef()
  // 分类数据
  const [data, setData] = useState([]);
  // 分页
  const [currentPage, setCurrentPage] = useState(1)
  const [pageSize, setPageSize] = useState(5)
  const [total, setTotal] = useState()
  // 表单数据
  const columns = [
    {
      title: '序号',
      dataIndex: 'id',
      width: '25%',
    },
    {
      title: '分类名',
      dataIndex: 'cateName',
      width: '25%',
      editable: true,
    },
    {
      title: '是否启用',
      dataIndex: 'state',
      render: (_, record) => (
        <Switch
          disabled={!isEditing(record)}
          defaultChecked={record.state === 1}
          onChange={(checked) => handleSwitchChange(checked, record.key)}
        />
      ),
      width: '25%'
    },
    {
      title: '操作',
      dataIndex: 'action',
      render: (_, record) => {
        const editable = isEditing(record);
        return (
          <span>
            {editable ? (
              <Button
                onClick={() => save(record)}
                type='primary'
              >
                保存
              </Button>
            ) : (
              <Button
                onClick={() => edit(record)}
                type='primary'
              >
                编辑
              </Button>
            )}
            <Button
              onClick={() => delBtn(record)}
              style={{ marginLeft: 10 }}
              type='primary'
              danger
            >
              删除
            </Button>
          </span>
        );
      },
    },
  ];
  // 分页改变事件
  const onPageChange = (page, pageSize) => {
    setCurrentPage(page);
    setPageSize(pageSize);
  };
  // 获取分类列表
  const cateList = async (value) => {
    let res = await goodsCateList(value)
    setTotal(res.data.total)
    let list = res.data.data
    const newData = list.map(item => ({
      key: item.id,
      id: item.id,
      cateName: item.cateName,
      state: item.state
    }))
    setData(newData)
  }

  // 添加分类对话框
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [initialState, setInitialState] = useState('true')
  // 打开对话框
  const addModal = () => {
    setIsModalOpen(true);
  }
  // 点击确认按钮
  const handleOk = () => {
    // 分类名
    const cateName = addRef.current.getFieldValue('cateName')
    const state = initialState
    add({ cateName, state })
    setIsModalOpen(false);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  // switch改变修改initialState
  const onChange = (checked) => {
    setInitialState(checked)
  };
  // 添加分类
  const add = async (value) => {
    const res = await goodsAddCate(value)
    const { code, msg } = res.data
    if (code == 0) {
      message.open({
        type: 'success',
        content: msg,
      })
    } else {
      message.open({
        type: 'error',
        content: msg,
      })
    }
    cateList({ currentPage, pageSize })
  }

  // 商品编辑
  const EditableCell = ({
    editing,
    dataIndex,
    title,
    inputType,
    record,
    index,
    children,
    ...restProps
  }) => {
    const inputNode = inputType === 'number' ? <InputNumber /> : <Input />;
    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item
            name={dataIndex}
            style={{
              margin: 0,
            }}
            rules={[
              {
                required: true,
                message: `请输入 ${title}!`,
              },
            ]}
          >
            {inputNode}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };
  const [editingKey, setEditingKey] = useState('');
  const isEditing = (record) => record.key === editingKey;
  const edit = (record) => {
    form.setFieldsValue({
      cateName: record.cateName,
      state: record.state
    });
    setEditingKey(record.key);
  };
  const save = async (value) => {
    const { key, id, state } = value
    const row = await form.validateFields();
    const cateName = row.cateName
    // 修改分类
    const res = await goodsEditCate({ id, cateName, state })
    const { code, msg } = res.data
    if (code == 0) {
      message.open({
        type: 'success',
        content: msg,
      })
    } else {
      message.open({
        type: 'error',
        content: msg,
      })
    }
    const newData = [...data];
    const index = newData.findIndex((item) => key === item.key);
    if (index > -1) {
      const item = newData[index];
      newData.splice(index, 1, {
        ...item,
        ...row,
      });
      setData(newData);
      setEditingKey('');
    } else {
      newData.push(row);
      setData(newData);
      setEditingKey('');
    }
  };
  const handleSwitchChange = (checked, key) => {
    const newData = data.map(item => {
      if (item.key === key) {
        return { ...item, state: checked ? 1 : 0 };
      }
      return item;
    });
    setData(newData);
  };
  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record) => ({
        record,
        inputType: col.dataIndex === 'age' ? 'number' : 'text',
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });

  // 商品删除
  const delBtn = (e) => {
    const id = e.key
    del({ id })
  }
  // 删除接口
  const del = async (value) => {
    const res = await goodsDelCate(value)
    const { code, msg } = res.data
    if (code == 0) {
      message.open({
        type: 'success',
        content: msg,
      })
    } else {
      message.open({
        type: 'error',
        content: msg,
      })
    }
    cateList({ currentPage, pageSize })
  }

  useEffect(() => {
    cateList({ currentPage, pageSize })
  }, [currentPage, pageSize])

  return (
    <>
      <Panner>
        <div slot='title'>商品分类</div>
        <Button style={{ height: 40 }} slot='btn' onClick={addModal}>添加分类</Button>

        <Modal title="添加分类" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
          <Form
            labelCol={{
              span: 5,
            }}
            wrapperCol={{
              span: 14,
            }}
            ref={addRef}
          >
            <Form.Item label='分类名' name='cateName'>
              <Input></Input>
            </Form.Item>
            <Form.Item label='是否启用' name='state'>
              <Switch
                defaultChecked
                onChange={onChange}
              />
            </Form.Item>
          </Form>
        </Modal>

        <Form form={form} component={false}>
          <Table
            components={{
              body: {
                cell: EditableCell,
              },
            }}
            bordered
            dataSource={data}
            columns={mergedColumns}
            rowClassName="editable-row"
            pagination={false} // 禁用分页
          />
        </Form>

        <Pagination
          total={total}
          defaultPageSize={5}
          pageSizeOptions={[5, 10, 20, 30]}
          showSizeChanger
          showQuickJumper
          showTotal={(total) => `共 ${total} 条`}
          onChange={onPageChange}
          style={{ marginTop: 5 }}
        />
      </Panner>
    </>
  )
}
